package cs340.stormtroopers.junitTests;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import junit.framework.TestCase;
import cs340.stormtroopers.database.HyPeerWebDatabase;
import cs340.stormtroopers.hypeerweb.CompleteNodeDomain;
import cs340.stormtroopers.hypeerweb.Node;

public class HyPeerWebDatabaseTests extends TestCase
{

	private HyPeerWebDatabase db;

	protected void setUp() throws Exception
	{
		super.setUp();
		HyPeerWebDatabase.initHyPeerWebDatabase("db_test_cases.sqlite");
		db = HyPeerWebDatabase.getSingleton();
		db.clear();
	}

	protected void tearDown() throws Exception
	{
		super.tearDown();
		db.close();
	}

	public void testAddingNodeToDatabase() throws SQLException, IOException, ClassNotFoundException
	{
		db.clear();
		Node n = new Node(0);
		Node n1 = new Node(1);
		n.addNeighbor(n1);
		n1.addNeighbor(n);
		Set<Node> nodes = new HashSet<Node>();
		nodes.add(n);
		nodes.add(n1);
		db.saveNodes(nodes);
	}

	public void testStoringAndReloadingOneNode() throws SQLException, IOException, ClassNotFoundException
	{
		db.clear();
		Node n4 = new Node(4);
		Node n2 = new Node(2);
		n4.addDownPointer(n2);
		ArrayList<Node> nodes = new ArrayList<Node>();
		nodes.add(n2);
		nodes.add(n4);
		db.saveNodes(nodes);

		// now we test getting one specific node from the DB
		CompleteNodeDomain n4reloaded = null;
		for (CompleteNodeDomain nd : db.getCompleteNodeDomainSet())
		{
			if (nd.getWebId() == 4)
				n4reloaded = nd;
		}
		assertTrue(n4reloaded != null);
		assertTrue(n4reloaded.getDownPointers().contains(new Integer(2)));
	}
}
